<template>
<el-card :title="选择登录用户">
    <template #default>
      <el-row style="text-align: center">
          <el-col :offset="8" :span="6">
              <el-form-item label="用户">
                  <el-select v-model="choseUserId">
                      <el-option :value="user.userId" :label="user.username" v-for="user in users"/>
                  </el-select>
              </el-form-item>
              <el-form-item>
                  <el-button @click="login">登录</el-button>
              </el-form-item>
          </el-col>
      </el-row>
    </template>
</el-card>
</template>

<script setup>
import loginRequest from "@/api/login.js";
import {onMounted, ref} from "vue";
import {useRouter} from 'vue-router';
import {ElMessage} from "element-plus";
// 保存所有用户列表
let users = ref([]);
// 保存选择的用户编号
let choseUserId = ref();

let router = useRouter();
// 模拟登录
function login(){
    if(choseUserId.value== undefined){
        ElMessage({
            type:"info",
            message:"请选择一个用户再登录"
        });
        return;
    }
    // 将用户信息保存到localStorage中
    let loginUser = undefined;
    users.value.forEach(user=>{
        console.log(user)
        if(user.userId == choseUserId.value){
            loginUser = user;
            console.log(loginUser)
        }
    });
    // 将选择的用户信息保存到localStorage中
    localStorage.setItem("userId",choseUserId.value);
    localStorage.setItem("username",loginUser.username);
    // 跳转到home页面
    router.push("/home/welcome");
}
/**
 * 加载所有用户信息
 */
function loadUsers(){
    loginRequest.loadUsers(res=>{
        users.value = res.data;
    });
}
onMounted(()=>{
    loadUsers();
})
</script>

<style scoped>

</style>